<template>
  <div class="divBox">
    <el-card class="box-card" shadow="never">
      <!-- <parser v-if="isShow" class="formBox" :form-conf="formConf" :form-edit-data="formData" :is-edit="isCreate === 1" @submit="submit" /> -->
      <el-form
        ref="formConf"
        v-loading="fullscreenLoading"
        class="formValidate mt20"
        :rules="ruleValidate"
        :model="formConf"
        label-width="150px"
        @submit.native.prevent
      >
        <el-col :span="13">
          <el-form-item
            label="投票标题："
            prop="title"
            :rules="ruleValidate.title"
          >
            <el-input
              v-model="formConf.title"
              maxlength="50"
              placeholder="请输入投票标题"
            />
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item
            label="投票副标题："
            prop="subtitle"
            :rules="ruleValidate.subtitle"
          >
            <el-input
              v-model="formConf.subtitle"
              maxlength="50"
              placeholder="请输入投票副标题"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="投票轮播图：" prop="cover">
            <div class="acea-row">
              <div
                v-for="(item, index) in formConf.cover"
                :key="index"
                class="pictrue"
                draggable="true"
                @dragstart="handleDragStart($event, item)"
                @dragover.prevent="handleDragOver($event, item)"
                @dragenter="handleDragEnter($event, item)"
                @dragend="handleDragEnd($event, item)"
              >
                <img :src="item" />
                <i class="el-icon-error btndel" @click="handleRemove(index)" />
              </div>
              <div
                v-if="formConf.cover.length < 10"
                class="upLoadPicBox"
                @click="modalPicTap(2)"
              >
                <div class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="投票日期：" prop="timer">
            <el-date-picker
              class="selWidth"
              v-model="formConf.timer"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              size="small"
              type="daterange"
              placement="bottom-end"
              :picker-options="pickerOptions"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="onchangeTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计票方式：" required>
            <el-radio-group v-model="formConf.field110">
              <el-radio :label="1" class="radio">按天</el-radio>
              <el-radio :label="2">全部</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最大投票数：" prop="maxNum">
            <el-input-number
              v-model="formConf.maxNum"
              :step="1"
              step-strictly
              :min="1"
              placeholder="请输入最大投票数"
              class="selWidth"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否报名审核：" required>
            <el-radio-group v-model="formConf.shen">
              <el-radio :label="1" class="radio">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报名仅限门店会员：" required>
            <el-radio-group v-model="formConf.xian">
              <el-radio :label="1" class="radio">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否门店排行：" required>
            <el-radio-group v-model="formConf.pai">
              <el-radio :label="1" class="radio">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="投票规则：" prop="rules">
            <el-input
              v-model="formConf.rules"
              type="textarea"
              maxlength="400"
              :rows="3"
              placeholder="请输入投票规则"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="投票详情：" prop="content">
            <el-input
              v-model="formConf.content"
              type="textarea"
              maxlength="400"
              :rows="3"
              placeholder="请输入投票详情"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="赠送优惠券：" class="proCoupon">
            <div v-if="formConf.coupons.length>0">
               <el-table :data="formConf.coupons" style="width: 100%" size="mini" border>
              <el-table-column
                label="优惠劵名称"
                align="center"
              >
                <template slot-scope="scope">
                  <div style="cursor: pointer;" @click="addCoupon">
                    {{ scope.row.name }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="数量"
                align="center"
              >
                <template slot-scope="scope">
                  <div>
                    <el-input-number
                :min="1"
                v-model="scope.row.number"
              ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
              >
              <template slot-scope="scope">
                <el-button @click="handleCloseCoupon(scope.$index)" size="mini">删除</el-button>
              </template>
              </el-table-column>
            </el-table>
            </div>
            <div class="acea-row" v-else>
              <!-- <el-tag
                v-for="(tag, index) in formConf.coupons"
                :key="index"
                class="mr10 mb10"
                closable
                :disable-transitions="false"
                @close="handleCloseCoupon(tag)"
              >
                {{ tag.name }}
              </el-tag> -->
              <el-button class="mr15" size="mini" @click="addCoupon"
                >选择优惠券</el-button
              >
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="赠送商品：" class="proCoupon">
            <div v-if="formConf.gifts.length>0">
              <el-table :data="formConf.gifts" style="width: 100%" size="mini" border>
              <el-table-column
                label="商品名"
                align="center"
              >
                <template slot-scope="scope">
                  <div @click="zengpin" style="cursor: pointer;">
                    {{ scope.row.name }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="商品规格"
                align="center"
                prop="attrValues"
              />
              <el-table-column
                label="数量"
                align="center"
              >
                <template slot-scope="scope">
                  <div>
                    <el-input-number
                :min="1"
                v-model="scope.row.number"
              ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
              >
              <template slot-scope="scope">
                <el-button @click="shanchu(scope.$index)" size="mini">删除</el-button>
              </template>
              </el-table-column>
            </el-table>
            </div>
            
            <div class="acea-row" v-else>
                <!-- <el-tag
                  v-for="(tag, index) in formConf.gifts"
                  :key="index"
                  class="mr10 mb10"
                  closable
                  :disable-transitions="false"
                  @close="shanchu(tag)"
                >
                  {{ tag.name }}
                </el-tag> -->
                <el-button class="mr15" size="mini" @click="zengpin">选择赠品</el-button>
              </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="成功跳转链接：">
            <el-select
              v-model="lianurl"
              placeholder="请选择"
              style="width: 250px"
              class="selWidth"
              clearable
              filterable
              v-if="zidingshow"
            >
              <el-option
                :value="item.url"
                maxlength="250"
                v-for="(item, index) in levelList"
                :key="index"
                :label="item.name"
              ></el-option>
            </el-select>
            <el-input
              v-model="formConf.lianjieId"
              style="width: 150px; margin-left: 20px"
              placeholder="请输入商品ID"
              v-if="shangshow"
            />
            <el-button
              type="primary"
              class="submission"
              @click="ziding"
              v-if="zidingshow"
              >自定义跳转链接</el-button
            >
            <el-input
              v-model="lianurl"
              maxlength="250"
              style="width: 400px"
              placeholder="自定义链接，不能跳转预约、购物车、个人中心"
              v-if="!zidingshow"
            />
            <el-button
              type="primary"
              class="submission"
              @click="ziding"
              v-if="!zidingshow"
              >返回</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="链接跳转方式：">
            <el-radio-group v-model="formConf.fang">
              <el-radio :label="1" class="radio">每次投票成功跳转</el-radio>
              <el-radio :label="2">次数用完后跳转</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="padding: 0 0 20px 120px">
          <el-button type="primary" class="submission" @click="submit(formConf)"
            >提交</el-button
          >
        </el-col>
      </el-form>
    </el-card>
    <!-- <CreatTemplates ref="addTemplates" @getList="getShippingList" /> -->
    <el-dialog
      :visible.sync="modals"
      title="商品列表"
      footerHide
      class="paymentFooter"
      scrollable
      width="900"
      @on-cancel="cancel"
      style="height: 800px"
    >
      <GoodList
        ref="Goodslist"
        @getStoreItem="getStoreItem"
        :handleNum="handleNum"
        :skushow="true"
      />
    </el-dialog>
  </div>
</template>

<script>
// import parser from '@/components/FormGenerator/components/parser/Parser'
import GoodList from "@/components/goodList";
import CreatTemplates from "@/views/systemSetting/logistics/shippingTemplates/creatTemplates";
import * as systemFormConfigApi from "@/api/systemFormConfig.js";
import { configSaveForm, configInfo } from "@/api/systemConfig.js";
import { toupiaolie } from "@/api/marketing.js";
import { toupiaodetalis } from "@/api/marketing";
import { formatDates } from "@/utils";
export default {
  name: "Config",
  components: { CreatTemplates, GoodList },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() <
            new Date().setTime(new Date().getTime() - 3600 * 1000 * 24)
          );
        },
      },
      handleNum: "many",
      // 表单
      formConf: {
        cover: [], //轮播图
        coupons: [], //优惠劵
        gifts: [], //赠品
        title: "", //标题
        subtitle: "", //副标题
        timer: [], //投票时间
        startTime: "", //开始时间
        endTime: "", //结束时间
        field110: "", //计票方式
        maxNum: "", //最大投票数
        rules: "", //投票规则
        content: "", //投票详情
        fang: "", //跳转方式
        lianjieId: "", //跳转商品ID
        shen: "", //是否审核
        pai: "", //是否门店排名
        xian: "", //是否仅限门店会员
      },
      lianurl: "", //跳转链接
      levelList: [
        { id: 1, name: "首页", url: "/pages/index/index" },
        { id: 2, name: "砍价", url: "/pages/activity/goods_bargain/index" },
        { id: 3, name: "拼团", url: "/pages/activity/goods_combination/index" },
        { id: 4, name: "秒杀", url: "/pages/activity/goods_seckill/index" },
        { id: 5, name: "商品详情", url: "/pages/goods_details/index?id=" },
        { id: 6, name: "优惠劵", url: "/pages/users/user_get_coupon/index" },
      ],
      formId: 134,
      formData: {},
      isCreate: 0,
      isShow: false,
      id: "",
      timer: [],
      fullscreenLoading: false,
      ruleValidate: {
        title: [{ required: true, message: "请输入投票标题", trigger: "blur" }],
        subtitle: [
          { required: true, message: "请输入投票副标题", trigger: "blur" },
        ],
        cover: [
          {
            required: true,
            message: "请上传商品轮播图",
            type: "array",
            trigger: "change",
          },
        ],
        timer: [
          {
            required: true,
            message: "请选择投票日期",
            type: "array",
            trigger: "change",
          },
        ],
        maxNum: [
          { required: true, message: "请输入投票次数", trigger: "blur" },
        ],
        rules: [{ required: true, message: "请输入投票规则", trigger: "blur" }],
        content: [
          { required: true, message: "请输入投票详情", trigger: "blur" },
        ],
        field110: [
          { required: true, message: "请选择计票方式", trigger: "blur" },
        ],
        shen: [
          { required: true, message: "请选择是否报名审核", trigger: "blur" },
        ],
        pai: [
          { required: true, message: "请选择是否门店排名", trigger: "blur" },
        ],
        xian: [
          {
            required: true,
            message: "请选择报名是否仅限门店会员",
            trigger: "blur",
          },
        ],
      },
      modals: false,
      field110: "",
      shangshow: false,
      zidingshow: true,
    };
  },
  created() {
    // systemFormConfigApi.getFormConfigInfo({ id: this.formId }).then(data => {
    //   this.formConf = JSON.parse(data.content)
    //   this.isShow=true
    // })
    if (window.location.search.split("=")[1]) {
      this.id = window.location.search.split("=")[1];
      this.getFormInfo();
    }
  },
  watch: {
    lianurl(val) {
      console.log(val);
      if (val == "/pages/goods_details/index?id=") {
        this.shangshow = true;
      } else {
        this.shangshow = false;
      }
    },
  },
  methods: {
    //自定义链接
    ziding() {
      this.zidingshow = !this.zidingshow;
      this.shangshow = false;
      this.lianurl = "";
    },
    //导入商品
    getStoreItem(row) {
      console.log(row)
      let ka = [];
      for (let i = 0; i < row.length; i++) {
        ka.push({
          entityId: row[i].id,
          name: row[i].name,
          number: 1,
          attrValues:row[i].attrValues
        });
      }
      this.formConf.gifts = ka;
      this.modals = false;
       console.log("for11",this.formConf.gifts)
    },
    //删除赠品
    shanchu(tag) {
      // console.log("this.formValidate.zengping",this.formValidate.zengping)
      this.isAttr = true;
      this.formConf.gifts.splice(this.formConf.gifts.indexOf(tag), 1);
    },
    //赠品弹窗
    zengpin() {
      this.modals = true;
    },
    //赠品
    cancel() {
      this.modals = false;
    },
    //添加优惠劵
    addCoupon() {
      const _this = this;
      this.$modalCoupon(
        "wu",
        (this.keyNum += 1),
        this.formConf.coupons,
        function (row) {
          // console.log("row123",row)
          _this.formConf.couponIds = [];
          _this.formConf.coupons = [];
          row.map((item) => {
            _this.formConf.couponIds.push({
              id: item.id,
              name: item.name,
              number: 1,
            });
          _this.formConf.coupons.push({
            entityId: item.id,
              name: item.name,
              number: 1,
          })
          });
        },
        ""
      );
      console.log("1235", this.formConf);
    },
    //删除优惠劵
    handleCloseCoupon(tag) {
      this.isAttr = true;
      this.formConf.coupons.splice(this.formConf.coupons.indexOf(tag), 1);
      // this.formConf.couponIds.splice(this.formConf.couponIds.indexOf(tag), 1)
    },
    //删除轮播图
    handleRemove(i) {
      this.formConf.cover.splice(i, 1);
    },
    //添加轮播图
    modalPicTap(tit, num, i) {
      const _this = this;
      // _this.formConf.cover=[]
      this.$modalUpload(
        function (img) {
          console.log(_this.formConf.cover);
          if (tit === 2 && !num) {
            if (img.length > 10)
              return this.$message.warning("最多选择10张图片！");
            if (img.length + _this.formConf.cover.length > 10)
              return this.$message.warning("最多选择10张图片！");
            img.map((item) => {
              _this.formConf.cover.push(item.sattDir);
            });
          }
          console.log(_this.formConf);
        },
        tit,
        "content"
      );
    },
    // 具体日期
    onchangeTime(e) {
      this.formConf.timer = e;
      this.formConf.startTime = e ? e[0] : "";
      this.formConf.endTime = e ? e[1] : "";
    },
    submit(data) {
      console.log(data);
      // if(!data.title || !data.subtitle  || !data.field110 || !data.maxNum || data.rules || !data.cover || data.shen=="" || data.pai=="" || data.xian=="" || !data.content || !data.couponTitle){
      //  return this.$message.warning('请填写完整的投票信息')
      // }
      if (!data.title) {
        return this.$message.error("请输入投票标题");
      } else if (!data.subtitle) {
        return this.$message.error("请输入投票副标题");
      } else if (!data.cover) {
        return this.$message.error("请选择投票轮播图");
      } else if (!data.timer) {
        return this.$message.error("请选择投票日期");
      } else if (!data.field110) {
        return this.$message.error("请选择计票方式");
      } else if (!data.maxNum) {
        return this.$message.error("请输入最大投票数");
      } else if (data.shen == "") {
        return this.$message.error("请选择是否报名审核");
      } else if (data.pai == "") {
        return this.$message.error("请选择是否门店排名");
      } else if (data.xian == "") {
        return this.$message.error("请选择报名是否仅限门店会员");
      } else if (!data.rules) {
        return this.$message.error("请输入投票规则");
      } else if (!data.content) {
        return this.$message.error("请输入投票详情");
      }
      if (this.lianurl && !data.fang) {
        return this.$message.error("请选择跳转方式");
      }
      if (this.lianurl == "/pages/goods_details/index?id=" && !data.lianjieId) {
        return this.$message.error("请填写商品ID");
      }
      if (data.fang && !this.lianurl) {
        return this.$message.error("请选择跳转链接");
      }

      console.log("提交", data);
      if (data.field110 == 1) {
        this.field110 = "day";
      } else {
        this.field110 = "all";
      }
      // const tempArr = []
      // for (var key in data) {
      //   const obj = {}
      //   obj.name = key
      //   obj.title = key
      //   obj.value = data[key]
      //   tempArr.push(obj)
      // }
      // console.log("tem",tempArr)
      const _pram = {
        id: this.id,
        title: data.title,
        subtitle: data.subtitle,
        rules: data.rules,
        content: data.content,
        startTime: data.timer[0],
        endTime: data.timer[1],
        countMethod: this.field110,
        maxNum: data.maxNum,
        cover: data.cover[0],
        pics: data.cover,
        giftList: data.gifts,
        voucherList:data.coupons,
        // couponId: data.coupons.length > 0 ? data.coupons[0].id : "",
        // couponTitle: data.coupons.length > 0 ? data.coupons[0].name : "",
        redirectPid: data.lianjieId,
        redirectUrl: this.lianurl,
        redirectWay: data.fang,
        needAudit: data.shen == 1 ? true : false,
        showRank2: data.pai == 1 ? true : false,
        enableVip: data.xian == 1 ? true : false,
      };
      console.log(_pram);
      toupiaolie(_pram).then((res) => {
        // this.getFormInfo()
        this.$message.success("操作成功");
        window.history.go(-1);
      });
    },
    // 获取表单详情
    getFormInfo() {
      toupiaodetalis(this.id).then((res) => {
        console.log("投票详情",res);
        this.formConf.coupons=res.voucherList ?  res.voucherList : []
        // if (res.couponTitle) {
        //   this.formConf.coupons[0] = {
        //     name: res.couponTitle,
        //     id: res.couponId,
        //   };
        // }
        if (res.redirectUrl) {
          this.lianurl = res.redirectUrl;
          this.formConf.fang = res.redirectWay;
        }
        if (res.redirectPid) {
          this.formConf.lianjieId = res.redirectPid;
          this.shangshow = true;
        }
        // let k=res.pics
        this.formConf.title = res.title;
        (this.formConf.subtitle = res.subtitle),
          // this.formConf.cover=JSON.parmas(k),
          (this.formConf.timer = [res.startTime, res.endTime]),
          (this.formConf.field110 = res.countMethod == "day" ? 1 : 2),
          (this.formConf.maxNum = res.maxNum),
          (this.formConf.rules = res.rules),
          (this.formConf.content = res.content),
          (this.formConf.gifts = res.giftList ? res.giftList : []),
          (this.formConf.cover = JSON.parse(res.pics)),
          (this.formConf.shen = res.needAudit ? 1 : 2);
        this.formConf.pai = res.showRank2 ? 1 : 2;
        this.formConf.xian = res.enableVip ? 1 : 2;
        console.log("this.formConf", this.formConf);
        // let data={
        //   content:res.content,
        //   // cover:res.cover,
        //   field110:res.countMethod=='countMethod'?1:2,
        //   maxNum:res.maxNum,
        //   rules:res.rules,
        //   timer:[res.startTime,res.endTime],
        //   title:res.title,
        //   subtitle:res.subtitle
        // }
        this.isShow = false;
        // this.formData = data
        // console.log("fordata",this.formData)
        this.isCreate = 1;
        setTimeout(() => {
          // 让表单重复渲染待编辑数据
          this.isShow = true;
        }, 100);
      });
    },
  },
};
</script>

<style scope lang="scss">
.labeltop {
  .el-input-number--small {
    /*width: 172px !important;*/
    min-width: 132px !important;
  }
}

.proCoupon {
  .el-form-item__content {
    margin-top: 5px;
  }
}
.tabPic {
  width: 40px !important;
  height: 40px !important;
  img {
    width: 100%;
    height: 100%;
  }
}
.noLeft {
  .el-form-item__content {
    margin-left: 0 !important;
  }
}
.tabNumWidth {
  .el-input-number--medium {
    width: 121px !important;
  }
  .el-input-number__increase {
    width: 20px !important;
    font-size: 12px !important;
  }
  .el-input-number__decrease {
    width: 20px !important;
    font-size: 12px !important;
  }
  .el-input-number--medium .el-input__inner {
    padding-left: 25px !important;
    padding-right: 25px !important;
  }
  thead {
    line-height: normal !important;
  }
  .el-table .cell {
    line-height: normal !important;
  }
}
.selWidth {
  width: 80%;
}
.selWidthd {
  width: 300px;
}
.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
  }
}
.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  left: 46px;
  top: -4px;
}
.labeltop {
  .el-form-item__label {
    /*float: none !important;*/
    /*display: inline-block !important;*/
    /*margin-left: 120px !important;*/
    /*width: auto !important;*/
  }
}
.submission {
  margin-left: 20px;
}
</style>
